#coding:utf-8

from flask import Flask,request,abort,render_template
import hashlib
import xmltodict
import time
import urllib2
import json

#   常量
# 微信的token令牌
WECHAT_TOKEN = 'python'
WECHAT_APPID = 'wxa46f89d2e55f373a'
WECHAT_APPSECRET = '403acf02239caef6790bdd55e929f8a7'





app = Flask(__name__)

@app.route('/wechat8003',methods=['GET','POST'])
def wechat():
    '''设置微信接入'''

    #todo 第一步验证签名是否正确
    signature = request.args.get('signature')  #微信加密签名,用来验证
    timestamp = request.args.get('timestamp') #时间戳
    nonce = request.args.get('nonce') #随机数
    # echostr = request.args.get('echostr')  #随机字符串,只用get请求的时候验证
    print(signature,timestamp,nonce)

    if not all([signature, timestamp, nonce]):
        abort(400)

    list = [WECHAT_TOKEN, timestamp, nonce]
    list.sort()
    sha1 = hashlib.sha1()
    map(sha1.update, list)
    hashcode = sha1.hexdigest()

    if hashcode == signature:
        # 验证成功
        #todo 第二步判断是get请求还是post
        if request.method == 'GET':
            echostr = request.args.get('echostr')  # 随机字符串,只用get请求的时候验证
            if echostr:
                return echostr

        elif request.method == 'POST':
            #todo 第三步  post请求则进行相关的业务逻辑
            #todo 将发送过来的文本返回回去.
            #发送过来的是xml格式数据
            # xml_str = xmltodict(request.data)
            xml_dict = xmltodict.parse(request.data).get('xml')

            msgtype = xml_dict.get('MsgType')
            if msgtype == 'text':
                print(u'接收到文本信息')
                #如果是文本格式则返回对应的文本信息
                response_dict = {
                    'xml':{
                        'ToUserName':xml_dict['FromUserName'],
                        'FromUserName':xml_dict['ToUserName'],
                        'CreateTime':int(time.time()),
                        'MsgType':'text',
                        'Content':xml_dict['Content']
                    }
                }
                response_xml = xmltodict.unparse(response_dict)
                return response_xml
            if msgtype == 'image':
                print(u'接收到图片信息')
                print(u'图片mediaid:%s' % xml_dict['MediaId'])
                response_dict = {
                    'xml': {
                        'ToUserName': xml_dict['FromUserName'],
                        'FromUserName': xml_dict['ToUserName'],
                        'CreateTime': int(time.time()),
                        'MsgType': 'image',
                        'Image':{
                            'MediaId':xml_dict['MediaId']
                        }
                    }
                }
                response_xml = xmltodict.unparse(response_dict)
                return response_xml
            # if msgtype == 'voice':
            #     print(u'接收到语音信息')
            #     print(u'语音mediaid:%s' % xml_dict['MediaId'])
            #     response_dict = {
            #         'xml': {
            #             'ToUserName': xml_dict['FromUserName'],
            #             'FromUserName': xml_dict['ToUserName'],
            #             'CreateTime': int(time.time()),
            #             'MsgType': 'image',
            #             'Voice': {
            #                 'MediaId': xml_dict['MediaId']
            #             }
            #         }
            #     }
            #     response_xml = xmltodict.unparse(response_dict)
            #     return response_xml
            # if msgtype == 'video':
            #     print(u'接收到视频信息')
            #     print(u'视频mediaid:%s' % xml_dict['MediaId'])
            #     response_dict = {
            #         'xml': {
            #             'ToUserName': xml_dict['FromUserName'],
            #             'FromUserName': xml_dict['ToUserName'],
            #             'CreateTime': int(time.time()),
            #             'MsgType': 'video',
            #             'Video': {
            #                 'MediaId': xml_dict['MediaId']
            #             }
            #         }
            #     }
            #     response_xml = xmltodict.unparse(response_dict)
            #     return response_xml




            return 'success'

    else:
        return ""


# 消息发送过来的请求,包含signature  timestamp  nonce  openid
# /wechat8003?signature=9afe99f0f5ecf73a13adeb653f5c07dcabbde011&timestamp=1511335295&nonce=1871917300&openid=oHGJN0eaHnzFRuyjtNUlNCdDSSh8


#用于进行微信认证
# https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect


redirect_uri = 'http://www.itcastcpp.cn/wechat8003/index'

#构造点击链接:
'''
https://open.weixin.qq.com/connect/oauth2/authorize?
appid=wxa46f89d2e55f373a&redirect_uri=http%3A//www.itcastcpp.cn/wechat8003/index
&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
'''



@app.route('/wechat8003/index')
def index():
    '''
    跳转过来的链接为:
    http%3A//www.itcastcpp.cn/wechat8003/index
    /?code=CODE&state=STATE
    '''
    # 先获取code
    code = request.args.get('code')
    if not code:
        return 'code 未核实'

    print(u'code获取成功:',code)

    #请求access_token
    get_token_url = """https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code"""\
                    % (WECHAT_APPID,WECHAT_APPSECRET,code)

    print(u'url',get_token_url)


    response = urllib2.urlopen(get_token_url)
    json_data = response.read()  #读取相应的json数据
    print(u'json_data--------------------------------------',json_data)



    json_dict = json.loads(json_data)
    if 'errcode' in json_dict:
        return u'获取token失败'

    access_token = json_dict.get('access_token')
    openid = json_dict.get('openid')
    print(u'access_token获取成功:',access_token)
    print(u'openid获取成功:', openid)


    #拉取用户信息
    get_token_url = '''https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN'''\
                    % (access_token,openid)
    response = urllib2.urlopen(get_token_url)
    json_data = response.read()  # 读取相应的json数据
    json_dict = json.loads(json_data)
    if 'errcode' in json_dict:
        return '获取token失败'
    print(u'获取的用户信息:',json_dict)
    #用户信息就为json_data
    return render_template('index.html',user=json_dict)



if __name__ == '__main__':
    app.run(port=8003,debug=True)



